<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title>销售预测与分析</title>
    <style>
        .stats-card {
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            height: 100%;
        }
        .stats-value {
            font-size: 28px;
            font-weight: bold;
            margin: 10px 0;
        }
        .stats-title {
            color: #6c757d;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .stats-change {
            font-size: 13px;
        }
        .stats-up {
            color: #28a745;
        }
        .stats-down {
            color: #dc3545;
        }
        .chart-container {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        .chart-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #343a40;
        }
        .filter-panel {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .chart-legend {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            margin-top: 10px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            margin-right: 15px;
            margin-bottom: 5px;
            font-size: 12px;
        }
        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
            margin-right: 5px;
        }
        .sale-funnel {
            padding: 20px 40px;
            position: relative;
        }
        .funnel-stage {
            margin-bottom: 10px;
            position: relative;
            display: flex;
            align-items: center;
        }
        .funnel-bar {
            background-color: #007bff;
            height: 40px;
            border-radius: 4px;
            position: relative;
            transition: width 1s ease-in-out;
        }
        .funnel-label {
            position: absolute;
            left: 15px;
            color: #fff;
            font-weight: bold;
            z-index: 1;
            display: flex;
            align-items: center;
            height: 100%;
        }
        .funnel-value {
            position: absolute;
            right: 15px;
            color: #fff;
            font-weight: bold;
            z-index: 1;
            display: flex;
            align-items: center;
            height: 100%;
        }
        .target-progress {
            margin: 15px 0;
        }
        .progress-bar-container {
            width: 100%;
            background-color: #e9ecef;
            border-radius: 4px;
            height: 8px;
            margin: 8px 0;
        }
        .progress-bar {
            height: 100%;
            border-radius: 4px;
            background-color: #28a745;
            transition: width 0.5s ease-in-out;
        }
        .progress-labels {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #6c757d;
        }
        .forecast-table {
            width: 100%;
            border-collapse: collapse;
        }
        .forecast-table th, .forecast-table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }
        .forecast-table th {
            background-color: #f8f9fa;
        }
        .probability-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="content-header">
            <h1>销售预测与分析</h1>
            <div class="filter-panel">
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="timeRange">时间范围</label>
                            <select id="timeRange" class="form-control">
                                <option value="week">本周</option>
                                <option value="month" selected>本月</option>
                                <option value="quarter">本季度</option>
                                <option value="year">本年</option>
                                <option value="custom">自定义范围</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="salesTeam">销售团队</label>
                            <select id="salesTeam" class="form-control">
                                <option value="all">所有团队</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="dateRange">自定义日期范围</label>
                            <div class="input-group">
                                <input type="date" id="startDate" class="form-control" disabled>
                                <div class="input-group-prepend input-group-append">
                                    <span class="input-group-text">至</span>
                                </div>
                                <input type="date" id="endDate" class="form-control" disabled>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button id="btnApplyFilters" class="btn btn-primary btn-block">应用筛选</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据总览卡片 -->
        <div class="row">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-title">新增销售机会</div>
                    <div class="stats-value">53</div>
                    <div class="stats-change stats-up">
                        <i class="fas fa-arrow-up"></i> 12% 较上期
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-title">预计成交额</div>
                    <div class="stats-value">¥235,600</div>
                    <div class="stats-change stats-up">
                        <i class="fas fa-arrow-up"></i> 8% 较上期
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-title">成交数量</div>
                    <div class="stats-value">27</div>
                    <div class="stats-change stats-down">
                        <i class="fas fa-arrow-down"></i> 3% 较上期
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-title">平均成交周期</div>
                    <div class="stats-value">32<span style="font-size: 16px;"> 天</span></div>
                    <div class="stats-change stats-up">
                        <i class="fas fa-arrow-up"></i> 2 天 较上期
                    </div>
                </div>
            </div>
        </div>

        <!-- 销售漏斗和销售趋势 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">销售漏斗</div>
                    <div class="sale-funnel" id="salesFunnel">
                        <!-- 漏斗将通过JS动态生成 -->
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">销售额趋势</div>
                    <canvas id="salesTrendChart" height="250"></canvas>
                    <div class="chart-legend">
                        <div class="legend-item">
                            <div class="legend-color" style="background-color: #4e73df;"></div>
                            <span>实际销售额</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background-color: #1cc88a;"></div>
                            <span>目标销售额</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background-color: #f6c23e;"></div>
                            <span>预测销售额</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 销售目标进度和团队绩效 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">销售目标进度</div>
                    <div id="targetProgress">
                        <div class="target-progress">
                            <div class="d-flex justify-content-between">
                                <span>月度销售额目标</span>
                                <span>75% (¥300,000 / ¥400,000)</span>
                            </div>
                            <div class="progress-bar-container">
                                <div class="progress-bar" style="width: 75%; background-color: #4e73df;"></div>
                            </div>
                        </div>

                        <div class="target-progress">
                            <div class="d-flex justify-content-between">
                                <span>新客户目标</span>
                                <span>60% (30 / 50)</span>
                            </div>
                            <div class="progress-bar-container">
                                <div class="progress-bar" style="width: 60%; background-color: #1cc88a;"></div>
                            </div>
                        </div>

                        <div class="target-progress">
                            <div class="d-flex justify-content-between">
                                <span>合同签订目标</span>
                                <span>90% (27 / 30)</span>
                            </div>
                            <div class="progress-bar-container">
                                <div class="progress-bar" style="width: 90%; background-color: #f6c23e;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">团队绩效对比</div>
                    <canvas id="teamPerformanceChart" height="250"></canvas>
                </div>
            </div>
        </div>

        <!-- 销售预测表 -->
        <div class="row">
            <div class="col-12">
                <div class="chart-container">
                    <div class="chart-title">销售机会预测</div>
                    <div class="table-responsive">
                        <table class="forecast-table">
                            <thead>
                                <tr>
                                    <th>客户名称</th>
                                    <th>机会名称</th>
                                    <th>阶段</th>
                                    <th>预计金额</th>
                                    <th>赢单概率</th>
                                    <th>预计成交日期</th>
                                    <th>负责人</th>
                                </tr>
                            </thead>
                            <tbody id="forecastTableBody">
                                <!-- 预测数据将通过JS动态生成 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <!-- 引入 Chart.js -->
        <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
        
        <script th:inline="javascript">
            document.addEventListener('DOMContentLoaded', function() {
                // 监听时间范围选择变化
                document.getElementById('timeRange').addEventListener('change', function() {
                    const customDateInputs = document.querySelectorAll('#startDate, #endDate');
                    
                    if (this.value === 'custom') {
                        customDateInputs.forEach(input => input.disabled = false);
                    } else {
                        customDateInputs.forEach(input => input.disabled = true);
                    }
                });
                
                // 初始化日期控件
                const today = new Date();
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                
                document.getElementById('startDate').valueAsDate = firstDayOfMonth;
                document.getElementById('endDate').valueAsDate = today;
                
                // 加载销售团队数据
                loadSalesTeams();
                
                // 应用筛选按钮事件
                document.getElementById('btnApplyFilters').addEventListener('click', function() {
                    loadAnalyticsData();
                });
                
                // 初始加载数据
                loadAnalyticsData();
            });
            
            // 加载销售团队
            function loadSalesTeams() {
                fetch('/api/sales/team/list')
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200 && data.data) {
                            const teamsSelect = document.getElementById('salesTeam');
                            
                            data.data.forEach(team => {
                                const option = document.createElement('option');
                                option.value = team.id;
                                option.textContent = team.name;
                                teamsSelect.appendChild(option);
                            });
                        }
                    })
                    .catch(error => console.error('Error loading teams:', error));
            }
            
            // 加载分析数据
            function loadAnalyticsData() {
                // 在实际应用中，这里应该发送请求获取实际数据
                // 这里使用模拟数据进行演示
                
                // 加载销售漏斗数据
                loadSalesFunnel();
                
                // 加载销售趋势图表
                loadSalesTrendChart();
                
                // 加载团队绩效图表
                loadTeamPerformanceChart();
                
                // 加载销售预测表
                loadSalesForecast();
            }
            
            // 加载销售漏斗
            function loadSalesFunnel() {
                // 模拟漏斗数据
                const funnelData = [
                    { stage: '初步接触', count: 120, color: '#4e73df' },
                    { stage: '需求确认', count: 85, color: '#1cc88a' },
                    { stage: '方案制定', count: 64, color: '#36b9cc' },
                    { stage: '商务谈判', count: 42, color: '#f6c23e' },
                    { stage: '合同签订', count: 27, color: '#e74a3b' }
                ];
                
                const funnelContainer = document.getElementById('salesFunnel');
                funnelContainer.innerHTML = '';
                
                // 找出最大值，用于计算百分比
                const maxCount = Math.max(...funnelData.map(item => item.count));
                
                // 生成漏斗各阶段
                funnelData.forEach((item, index) => {
                    const percentage = (item.count / maxCount) * 100;
                    
                    const funnelStage = document.createElement('div');
                    funnelStage.className = 'funnel-stage';
                    
                    const funnelBar = document.createElement('div');
                    funnelBar.className = 'funnel-bar';
                    funnelBar.style.width = '0%';
                    funnelBar.style.backgroundColor = item.color;
                    
                    const funnelLabel = document.createElement('div');
                    funnelLabel.className = 'funnel-label';
                    funnelLabel.textContent = item.stage;
                    
                    const funnelValue = document.createElement('div');
                    funnelValue.className = 'funnel-value';
                    funnelValue.textContent = item.count;
                    
                    funnelBar.appendChild(funnelLabel);
                    funnelBar.appendChild(funnelValue);
                    funnelStage.appendChild(funnelBar);
                    funnelContainer.appendChild(funnelStage);
                    
                    // 动画效果
                    setTimeout(() => {
                        funnelBar.style.width = percentage + '%';
                    }, 100 * index);
                });
            }
            
            // 加载销售趋势图表
            function loadSalesTrendChart() {
                const ctx = document.getElementById('salesTrendChart').getContext('2d');
                
                // 销售趋势数据（模拟数据）
                const salesData = {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                    datasets: [
                        {
                            label: '实际销售额',
                            data: [280000, 320000, 250000, 340000, 360000, 300000],
                            borderColor: '#4e73df',
                            backgroundColor: 'rgba(78, 115, 223, 0.05)',
                            pointBackgroundColor: '#4e73df',
                            pointBorderColor: '#fff',
                            pointRadius: 3,
                            pointHoverRadius: 5,
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '目标销售额',
                            data: [300000, 300000, 300000, 350000, 350000, 350000],
                            borderColor: '#1cc88a',
                            backgroundColor: 'rgba(28, 200, 138, 0)',
                            pointBackgroundColor: '#1cc88a',
                            pointBorderColor: '#fff',
                            pointRadius: 3,
                            pointHoverRadius: 5,
                            borderDash: [5, 5],
                            tension: 0.3,
                            fill: false
                        },
                        {
                            label: '预测销售额',
                            data: [null, null, null, null, null, 380000],
                            borderColor: '#f6c23e',
                            backgroundColor: 'rgba(246, 194, 62, 0.05)',
                            pointBackgroundColor: '#f6c23e',
                            pointBorderColor: '#fff',
                            pointRadius: 3,
                            pointHoverRadius: 5,
                            borderDash: [2, 2],
                            tension: 0.3,
                            fill: true
                        }
                    ]
                };
                
                // 销售趋势图表配置
                const config = {
                    type: 'line',
                    data: salesData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false,
                                callbacks: {
                                    label: function(context) {
                                        let label = context.dataset.label || '';
                                        if (label) {
                                            label += ': ';
                                        }
                                        if (context.parsed.y !== null) {
                                            label += '¥' + context.parsed.y.toLocaleString();
                                        }
                                        return label;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                grid: {
                                    drawBorder: false,
                                    display: false
                                }
                            },
                            y: {
                                ticks: {
                                    callback: function(value) {
                                        return '¥' + value.toLocaleString();
                                    }
                                },
                                grid: {
                                    borderDash: [2],
                                    drawBorder: false,
                                    color: 'rgba(0, 0, 0, 0.1)'
                                }
                            }
                        }
                    }
                };
                
                // 创建销售趋势图表
                new Chart(ctx, config);
            }
            
            // 加载团队绩效图表
            function loadTeamPerformanceChart() {
                const ctx = document.getElementById('teamPerformanceChart').getContext('2d');
                
                // 团队绩效数据（模拟数据）
                const teamData = {
                    labels: ['团队A', '团队B', '团队C', '团队D'],
                    datasets: [
                        {
                            label: '销售额',
                            data: [320000, 280000, 350000, 250000],
                            backgroundColor: [
                                'rgba(78, 115, 223, 0.7)',
                                'rgba(28, 200, 138, 0.7)',
                                'rgba(54, 185, 204, 0.7)',
                                'rgba(246, 194, 62, 0.7)'
                            ],
                            borderColor: [
                                'rgb(78, 115, 223)',
                                'rgb(28, 200, 138)',
                                'rgb(54, 185, 204)',
                                'rgb(246, 194, 62)'
                            ],
                            borderWidth: 1
                        }
                    ]
                };
                
                // 团队绩效图表配置
                const config = {
                    type: 'bar',
                    data: teamData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        let label = context.dataset.label || '';
                                        if (label) {
                                            label += ': ';
                                        }
                                        if (context.parsed.y !== null) {
                                            label += '¥' + context.parsed.y.toLocaleString();
                                        }
                                        return label;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                grid: {
                                    display: false
                                }
                            },
                            y: {
                                ticks: {
                                    callback: function(value) {
                                        return '¥' + value.toLocaleString();
                                    }
                                },
                                grid: {
                                    borderDash: [2],
                                    color: 'rgba(0, 0, 0, 0.1)'
                                }
                            }
                        }
                    }
                };
                
                // 创建团队绩效图表
                new Chart(ctx, config);
            }
            
            // 加载销售预测表
            function loadSalesForecast() {
                // 模拟销售预测数据
                const forecastData = [
                    {
                        customer: '上海禾辰科技有限公司',
                        opportunity: 'CRM系统升级项目',
                        stage: '商务谈判',
                        amount: 85000,
                        probability: 80,
                        closeDate: '2023-07-15',
                        owner: '张三'
                    },
                    {
                        customer: '北京智云数据科技有限公司',
                        opportunity: '数据分析平台定制开发',
                        stage: '方案制定',
                        amount: 120000,
                        probability: 65,
                        closeDate: '2023-07-30',
                        owner: '李四'
                    },
                    {
                        customer: '广州鼎新信息技术有限公司',
                        opportunity: '移动应用开发项目',
                        stage: '需求确认',
                        amount: 50000,
                        probability: 45,
                        closeDate: '2023-08-10',
                        owner: '王五'
                    },
                    {
                        customer: '深圳未来科技有限公司',
                        opportunity: '企业门户网站建设',
                        stage: '商务谈判',
                        amount: 68000,
                        probability: 75,
                        closeDate: '2023-07-20',
                        owner: '赵六'
                    },
                    {
                        customer: '杭州创新软件有限公司',
                        opportunity: '人力资源管理系统实施',
                        stage: '方案制定',
                        amount: 95000,
                        probability: 60,
                        closeDate: '2023-08-05',
                        owner: '孙七'
                    }
                ];
                
                const tableBody = document.getElementById('forecastTableBody');
                tableBody.innerHTML = '';
                
                forecastData.forEach(item => {
                    // 根据概率设置颜色
                    let probabilityColor;
                    if (item.probability >= 75) {
                        probabilityColor = '#1cc88a'; // 绿色
                    } else if (item.probability >= 50) {
                        probabilityColor = '#f6c23e'; // 黄色
                    } else {
                        probabilityColor = '#e74a3b'; // 红色
                    }
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.customer}</td>
                        <td>${item.opportunity}</td>
                        <td>${item.stage}</td>
                        <td>¥${item.amount.toLocaleString()}</td>
                        <td>
                            <div class="probability-dot" style="background-color: ${probabilityColor};"></div>
                            ${item.probability}%
                        </td>
                        <td>${item.closeDate}</td>
                        <td>${item.owner}</td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        </script>
    </th:block>
</body>
</html> 